package com.ccteam.shared.domain.moment.up

import com.ccteam.model.Resource
import com.ccteam.model.moment.up.MomentUpDTO
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.moment.MomentsRepository
import com.ccteam.shared.domain.SuspendUseCase
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/1
 */
class PublishMomentUpDataUseCase @Inject constructor(
    private val momentsRepository: MomentsRepository,
    private val userCore: UserCore
): SuspendUseCase<Pair<Boolean, String>, Nothing?>(
    Dispatchers.IO
) {
    override suspend fun execute(parameters: Pair<Boolean,String>): Resource<Nothing?> {
        val userInfo = userCore.userInfo.value
        val isLogin = userCore.isLogin.value

        if(!isLogin || userInfo.userToken.isNullOrEmpty() || userInfo.userId.isNullOrEmpty()){
            return Resource.Error(ApiError.unknownCode,"非法操作")
        }

        val (isUp,momentId) = parameters
        // 判断是点赞还是取消点赞
        val result = if(isUp){
            momentsRepository.setCommentUp(userInfo.userToken,
                MomentUpDTO(null,momentId,userInfo.userId)
            )
        } else {
            momentsRepository.cancelCommentUp(userInfo.userToken,
                momentId,userInfo.userId
            )
        }

        return when(result){
            is ApiResult.Success -> {
                Resource.Success(null)
            }
            is ApiResult.Failure -> {
                Resource.Error(result.errorCode,result.errorMsg)
            }
            else -> {
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
        }
    }
}